﻿using AnlianCommon.Common.Domains.OrganizationalUnits;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AnlianCommon.API.Commands.Departments
{
    public class DepartmentTreeQueryHandler : IRequestHandler<DepartmentTreeQueryCommand, Result>
    {
        private readonly IBaseRepository<DepartmentTree> _departmentTreeRepository;

        public DepartmentTreeQueryHandler(IBaseRepository<DepartmentTree> departmentTreeRepository)
        {
            _departmentTreeRepository = departmentTreeRepository;
        }
        /// <summary>
        /// 部门树形业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(DepartmentTreeQueryCommand request, CancellationToken cancellationToken)
        {
            //返回的响应码
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                //查询企业树形表信息 条件 父级ID  PID
                var departmentTree = await(await _departmentTreeRepository.GetAll()).Where(c => c.PId == 0).ToListAsync();
                //实例化级联数据源
                List<Cascard> cascards = new List<Cascard>();
                //历遍企业树形查到的企业树形信息
                foreach (var item in departmentTree)
                {
                    //实例化级联数据源
                    Cascard cascard = new Cascard();
                    cascard.value = item.DepartmentTreeId;//把企业树形Name赋值给级联数据源里的Value
                    cascard.label = item.DepartmentTreeName;//把企业树形ID赋值给级联数据源里的Label
                    cascard.children = await GetCascards(item.DepartmentTreeId);
                    cascards.Add(cascard);
                }
                result.Data = cascards;

            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
        public async Task<List<Cascard>> GetCascards(int pid = 0)
        {
            var departmentTree = await (await _departmentTreeRepository.GetAll()).Where(c => c.PId == pid).ToListAsync();
            List<Cascard> cascards = new List<Cascard>();
            foreach (var item in departmentTree)
            {
                Cascard cascard = new Cascard();
                cascard.value = item.DepartmentTreeId;//把企业树形Name赋值给级联数据源里的Value
                cascard.label = item.DepartmentTreeName;//把企业树形ID赋值给级联数据源里的Label
                cascard.children = await GetCascards(item.DepartmentTreeId);
                cascards.Add(cascard);
            }
            return cascards;
        }
    }
}
